$(function(){
    
    $(document).ready(function() {
        $('#fullpage').fullpage({
            verticalCentered: false,
            resize : false,
            anchors:['home', 'products', 'about', 'forum', 'contacts'],
            scrollingSpeed: 700,
            easing: 'easeInQuart',
            menu: '#menu',
            navigation: true,
            navigationPosition: 'right',
            scrollOverflow: true,
//            paddingTop: '14em',
            css3: true,
            afterLoad: function(anchorLink, index){

					// home view
					if(index == 1){
                        
						$('#menu a[href="#home"]').toggleClass('active');
                        $('#container-heading > h2').text('Начало');
                        
                        $('#scroll-down-anchor').attr({href: '#products', 'data-manuanchor': 'productsView'});
					}
                    // products view
                    if(index == 2){
                        
						$('#menu a[href="#products"]').toggleClass('active');
                        $('#container-heading > h2').text('Продукти');
                        
                        $('#scroll-down-anchor').attr({href: '#about', 'data-manuanchor': 'aboutView'});
					}
                    // about view
                    if(index == 3){
                        
						$('#menu a[href="#about"]').toggleClass('active');
                        $('#container-heading > h2').text('За нас');
                        
                        $('#scroll-down-anchor').attr({href: '#forum', 'data-manuanchor': 'forumView'});
					}
                    // forum view
                    if(index == 4){
                        
						$('#menu a[href="#forum"]').toggleClass('active');
                        $('#container-heading > h2').text('Форум');
                        
                        $('#scroll-down-anchor').attr({href: '#contacts', 'data-manuanchor': 'contactsView'});
					}
                    // contacts
                    if(index == 5){
                        
						$('#menu a[href="#contacts"]').toggleClass('active');
                        $('#container-heading > h2').text('Contacts');
					}
				}
        });
    });
    
    // assings molecule menu anchors attributes href and data-manuanchor
    $('body').one('mousemove', function() {
        
        $('#canvas-container > div').css('overflow', 'visible');
        
        $('#canvas-container a:nth-child(8)').attr({href: '#home', 'data-manuanchor': 'homeView', class: 'active'});
        $('#canvas-container a:nth-child(2)').attr({href: '#products', 'data-manuanchor': 'productsView'});
        $('#canvas-container a:nth-child(1)').attr({href: '#about', 'data-manuanchor': 'aboutView'});
        $('#canvas-container a:nth-child(4)').attr({href: '#forum', 'data-manuanchor': 'forumView'});
        $('#canvas-container a:nth-child(3)').attr({href: '#contacts', 'data-manuanchor': 'contactsView'});
    });
    
    // position scroll down icon
    var windowBottom = $(window).height() - 150;
    $('#scroll-down').css('top', windowBottom);
    
    // order form
    var formContainer = $('#form-container');
    var orderButton = $('.order-button');
    var closeButton = $('#close-button');
    var submitButton = $('#submit-button');
    var windowHeight = $(window).height();
    
    orderButton.on('click', function(e) {
        e.preventDefault();
        
        formContainer.show();
    });
    
    submitButton.on('click', function(e) {
        e.preventDefault();
        
        formContainer.hide();
    });
    
    closeButton.on('click', function() {
        formContainer.hide();
    });
    
    formContainer.css('height', windowHeight);
    
    // google maps config
    var myLatlng = new google.maps.LatLng(42.673334, 23.244787);
    var myOptions = {
        zoom: 13,
        center: myLatlng,
        scrollwheel: false,
        navigationControl: false,
        zoomControl: true,
        panControl: true,
        panControlOptions: {
            position: google.maps.ControlPosition.RIGHT_BOTTOM
        },
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL,
            position: google.maps.ControlPosition.RIGHT_BOTTOM
        },
        scrollwheel: false,  
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    var map = new google.maps.Map(document.getElementById("map"), myOptions);

    var contentString = '<div id="info-window">'+
        '<h3>Top Pharma</h3>' + 
        '<p>гр. София, ул. Акад. Маджаров 10</p>' + 
        '<p>02/ 86 20 192  02/ 40 84 012</p>' + 
//        '<p>02/ 40 84 012</p>' + 
        '</div>';

    var infowindow = new google.maps.InfoWindow({
        content: contentString
    });

    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title:"Top Pharma"
    });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map,marker);
    });
    infowindow.open(map,marker);

    //tabs control
    $('#tab1-link').on('click', function(e) {
        e.preventDefault();
        $('#tab1').addClass('active');
        $('#tab2').removeClass('active');
    });
    $('#tab2-link').on('click', function(e) {
         e.preventDefault();
        $('#tab2').addClass('active');
        $('#tab1').removeClass('active');
    });
    
    

}());

// treejs init and config
$(function() {
    
    var camera, scene, renderer;
			var controls;
			var root;

			var objects = [];
			var tmpVec1 = new THREE.Vector3();
			var tmpVec2 = new THREE.Vector3();
			var tmpVec3 = new THREE.Vector3();
			var tmpVec4 = new THREE.Vector3();

			var visualizationType = 2;

			var MOLECULES = {
				"Ethanol": "ethanol.pdb"
			};

			var loader = new THREE.PDBLoader();
			var colorSpriteMap = {};
			var baseSprite = document.createElement( 'img' );

//			var menu = document.getElementById( "menu" );

			init();
			animate();

			function init() {

				camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 5000 );
				camera.position.z = 1500;

				scene = new THREE.Scene();

				root = new THREE.Object3D();
				scene.add( root );

				//

				renderer = new THREE.CSS3DRenderer();
				renderer.setSize( 300, window.innerHeight );
				document.getElementById( 'canvas-container' ).appendChild( renderer.domElement );

				//

				controls = new THREE.TrackballControls( camera, renderer.domElement );
				controls.rotateSpeed = 0.01;
				controls.addEventListener( 'change', render );

				//

				baseSprite.onload = function () {

					loadMolecule( "./lib/models/ethanol.pdb" );
//					createMenu();

				};

				baseSprite.src = './lib/textures/snooker_ball.png';

				//

				window.addEventListener( 'resize', onWindowResize, false );

			}

			//

			function generateButtonCallback( url ) {

				return function ( event ) {

					loadMolecule( url );

				}

			}

			function showAtomsBonds() {

				for ( var i = 0; i < objects.length; i ++ ) {

					var object = objects[ i ];

					object.element.style.display = "";
					object.visible = true;

					if ( ! ( object instanceof THREE.CSS3DSprite ) ) {

						object.element.style.height = object.userData.bondLengthShort;

					}

				}

			}

			//

			function colorify( ctx, width, height, color, a ) {

				var r = color.r;
				var g = color.g;
				var b = color.b;

				var imageData = ctx.getImageData( 0, 0, width, height );
				var data = imageData.data;

				for ( var y = 0; y < height; y ++ ) {

					for ( var x = 0; x < width; x ++ ) {

						var index = ( y * width + x ) * 4;

						data[ index ]     *= r;
						data[ index + 1 ] *= g;
						data[ index + 2 ] *= b;
						data[ index + 3 ] *= a;

					}

				}

				ctx.putImageData( imageData, 0, 0 );

			}

			function imageToCanvas( image ) {

				var width = image.width;
				var height = image.height;

				var canvas = document.createElement( 'canvas' );

				canvas.width = width;
				canvas.height = height;

				var context = canvas.getContext( '2d' );
				context.drawImage( image, 0, 0, width, height );

				return canvas;

			}

			//

			function loadMolecule( url ) {

				for ( var i = 0; i < objects.length; i ++ ) {

					var object = objects[ i ];
					object.parent.remove( object );

				}

				objects = [];

				loader.load( url, function ( geometry, geometryBonds ) {

					var offset = geometry.center();
					geometryBonds.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );

					for ( var i = 0; i < geometry.vertices.length; i ++ ) {

						var position = geometry.vertices[ i ];
						var color = geometry.colors[ i ];
						var element = geometry.elements[ i ];

						if ( ! colorSpriteMap[ element ] ) {

							var canvas = imageToCanvas( baseSprite );
							var context = canvas.getContext( '2d' );

							colorify( context, canvas.width, canvas.height, color, 1 );

							var dataUrl = canvas.toDataURL();

							colorSpriteMap[ element ] = dataUrl;

						}

						colorSprite = colorSpriteMap[ element ];

                        var anchor = document.createElement('a');
						//var atom = document.createElement( 'img' );
                        //atom.appendChild(anchor);
						//atom.src = colorSprite;

						//var object = new THREE.CSS3DSprite( atom );
                        var object = new THREE.CSS3DSprite( anchor );
						object.position.copy( position );
						object.position.multiplyScalar( 120 );

						object.matrixAutoUpdate = false;
						object.updateMatrix();

						root.add( object );

						objects.push( object );

					}

					for ( var i = 0; i < geometryBonds.vertices.length; i += 2 ) {

						var start = geometryBonds.vertices[ i ];
						var end = geometryBonds.vertices[ i + 1 ];

						start.multiplyScalar( 120 );
						end.multiplyScalar( 120 );

						tmpVec1.subVectors( end, start );
						var bondLength = tmpVec1.length() - 60;


						//

						var bond = document.createElement( 'div' );
						bond.className = "bond";
						bond.style.height = bondLength + "px";

						var object = new THREE.CSS3DObject( bond );
						object.position.copy( start );
						object.position.lerp( end, 0.5 );

						object.userData.bondLengthShort = bondLength + "px";
						object.userData.bondLengthFull = ( bondLength + 55 ) + "px";

						//

						var axis = tmpVec2.set( 0, 1, 0 ).cross( tmpVec1 );
						var radians = Math.acos( tmpVec3.set( 0, 1, 0 ).dot( tmpVec4.copy( tmpVec1 ).normalize() ) );

						var objMatrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
						object.matrix = objMatrix;
						object.rotation.setFromRotationMatrix( object.matrix, object.rotation.order );

						object.matrixAutoUpdate = false;
						object.updateMatrix();

						root.add( object );

						objects.push( object );

						//

						var bond = document.createElement( 'div' );
						bond.className = "bond";
						bond.style.height = bondLength + "px";

						var joint = new THREE.Object3D( bond );
						joint.position.copy( start );
						joint.position.lerp( end, 0.5 );

						joint.matrix.copy( objMatrix );
						joint.rotation.setFromRotationMatrix( joint.matrix, joint.rotation.order );

						joint.matrixAutoUpdate = false;
						joint.updateMatrix();

						var object = new THREE.CSS3DObject( bond );
						object.rotation.y = Math.PI/2;

						object.matrixAutoUpdate = false;
						object.updateMatrix();

						object.userData.bondLengthShort = bondLength + "px";
						object.userData.bondLengthFull = ( bondLength + 55 ) + "px";

						object.userData.joint = joint;

						joint.add( object );
						root.add( joint );

						objects.push( object );

					}

					//console.log( "CSS3DObjects:", objects.length );

//					switch ( visualizationType ) {
//
//						case 0: showAtoms(); break;
//						case 1: showBonds(); break;
//						case 2: showAtomsBonds(); break;
//
//					}

					render();

				} );


			}

			//

			function onWindowResize() {

				camera.aspect = 300 / window.innerHeight;
				camera.updateProjectionMatrix();

				renderer.setSize( 300 , window.innerHeight );

//				render();

			}

			function animate() {

//				requestAnimationFrame( animate );
//				controls.update();
//
//				var time = 0.0001;
//
//				root.rotation.x = time / 8;
//				root.rotation.y = time / 0.4;
//
//				render();
                
                requestAnimationFrame( animate );
				controls.update();

				var time = Date.now() * 0.0004;

				//root.rotation.x = time;
				root.rotation.y = time * 0.7 / 8;

				render();

			}

			function render() {

				renderer.render( scene, camera );

			}
    
}());

